package com.uxsino.commons.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 枚举工具类
 */
public class EnumUtils {

    private static final Logger logger = LoggerFactory.getLogger(EnumUtils.class);

    /**
     * 枚举名称与值映射的列表
     * @param cls 枚举类
     * @param nameField 名称字段
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static List<Map<String, String>> nameValueList(Class cls, String nameField) {
        List<Map<String, String>> list = new ArrayList<>();
        try {
            if (!cls.isEnum()) {
                return list;
            }
            Object[] objArr = cls.getEnumConstants();
            if (objArr != null && objArr.length > 0) {
                Map<String, String> map = null;
                for (Object obj : objArr) {
                    map = new HashMap<>();
                    Field field = cls.getDeclaredField(nameField);
                    field.setAccessible(true);
                    map.put("name", field.get(obj).toString());
                    map.put("value", obj.toString());
                    list.add(map);
                }
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return list;
    }

}
